chrome.runtime.onInstalled.addListener(function(){
	chrome.tabs.create({
		url: chrome.runtime.getURL("instructions.html"),
	   selected: true
	});
});

function sendNotification(obj, callback){
	//countId必须为字符串，不能为数字
	let countId = Math.random() + ''
	chrome.notifications.create(countId, obj, callback);
	clearNotification(countId, 3)
}
function clearNotification(id, time){
	setTimeout(() => {
		chrome.notifications.clear(id);
	}, time * 1000)
}

chrome.runtime.onMessage.addListener((message, sender, callback) => {
	const icoPath = "external/images/yu.png"
	let tabId
	if("getInterval" === message){
		chrome.storage.sync.get("interval", result => {
			callback(result["interval"])
		});
	}else if("getRes" === message){
		chrome.storage.sync.get(["follow", "reply", "who", "what"], result => {
			callback(result)
		});
	}else if("tabId" === message){
		tabId = sender.tab.id;
	}else if("start" === message){
		sendNotification({//需要申请权限notifications，只能在后台中使用
					type:"basic",
					title:"雨课堂上课了",
					message:"已进入课堂",
					iconUrl:icoPath
				}, () => {});
		callback("");
	}else if("over" === message){
		sendNotification({//需要申请权限notifications，只能在后台中使用
					type:"basic",
					title:"雨课堂下课了",
					message:"已离开课堂重新监听",
					iconUrl:icoPath
				}, () => {});
	}else if("no" === message){
		sendNotification({//需要申请权限notifications，只能在后台中使用
					type:"basic",
					title:"老师未开启弹幕或不支持的弹幕类型",
					message:"会影响应答跟答功能",
					iconUrl:icoPath
				}, () => {});
	}else if("point" === message){
		sendNotification({//需要申请权限notifications，只能在后台中使用
					type:"basic",
					title:"点名点到你了",
					message:"若打开了自动应答则会自动回复",
					iconUrl:icoPath
				}, () => {});
	}else if("question" === message){
		sendNotification({//需要申请权限notifications，只能在后台中使用
					type:"basic",
					title:"老师发题了！",
					message:"(别TM摸鱼了)",
					iconUrl:icoPath
				}, () => {});
	}else if ("close" === message){
		sendNotification({//需要申请权限notifications，只能在后台中使用
			type:"basic",
			title:"老师关闭弹幕了！",
			message:"会影响应答跟答功能",
			iconUrl:icoPath
		}, () => {});
	}
	return true;
});

// chrome.tabs.onUpdated.addListener(function (id, info, tab) {
// 	const url = "https://www.yuketang.cn/lesson";
// 	if(tab.url.indexOf(url) !== -1){
// 		chrome.tabs.sendMessage(tabId, "urlChanged")
// 	}
// });